# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=orcus
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=0.20.0
pkgrel=1
pkgdesc="Standalone file import filter library for spreadsheet documents (ODS, XLSX and CSV). (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://gitlab.com/orcus/orcus'
msys2_references=(
  'archlinux: liborcus'
)
license=('spdx:MPL-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-boost-libs"
         "${MINGW_PACKAGE_PREFIX}-ixion"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-boost"
             "${MINGW_PACKAGE_PREFIX}-mdds"
             "${MINGW_PACKAGE_PREFIX}-python")
optdepends=("${MINGW_PACKAGE_PREFIX}-python: Python bindings")
source=("https://gitlab.com/orcus/orcus/-/archive/${pkgver}/${_realname}-${pkgver}.tar.bz2"
        "001-fix-build-on-mingw.patch"
        "003-do-not-search-for-boost-system.patch")
sha256sums=('767ddd06d72b18c5e6c65af74a78b8c7b9326c7163fde1066b97369769a68f35'
            '95b5ad424d9b1692f5013f78646347baf27e0a15ac3a4dd00885bd0b7a0ea050'
            '112f73f7695e9963913cd21f5245391529101a660a8f3b3fff805fb4958d5d21')

prepare() {
  cd ${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-build-on-mingw.patch
  patch -p1 -i "${srcdir}"/003-do-not-search-for-boost-system.patch

  autoreconf -fiv
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  export lt_cv_deplibs_check_method='pass_all'

  declare -a _extra_config
  if [[ ${CARCH} == x86_64 ]]; then
    _extra_config+=("--with-cpu-features")
  fi

  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --without-benchmark \
    "${_extra_config[@]}"

  make
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  make check || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" make install

  MSYS2_ARG_CONV_EXCL="-p" python -m compileall \
    -o 0 -o 1 -q -s"${pkgdir}" -p"/" "${pkgdir}${MINGW_PREFIX}/lib/python"*

  PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  find "${pkgdir}${MINGW_PREFIX}/lib/pkgconfig" -type f -name '*.pc' \
    -exec sed -i -e "s|${PREFIX_WIN}|\$\{prefix\}|g" {} \;

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    _pyver=$(${MINGW_PREFIX}/bin/python -c "import sys;sys.stdout.write('.'.join(map(str, sys.version_info[:2])))")
    # Use *.pyd extension for python modules
    for _dll in "${pkgdir}${MINGW_PREFIX}"/lib/python${_pyver}/site-packages/*.dll; do
      mv ${_dll} ${_dll/.dll/.pyd}
    done
    # remove unused import libraries
    rm -f "${pkgdir}${MINGW_PREFIX}"/lib/python${_pyver}/site-packages/*.dll.a
  fi

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
